package com.demo.elasticsearch;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class RandomUser {

	// https://randomuser.me/api/?results=5000
	public static JSONArray get(int num) {
		JSONObject obj = null;
		obj = JSONObject
				.parseObject(doGet("https://randomuser.me/api/?results=" + num));

		if (obj != null) {
			return obj.getJSONArray("results");
		}
		return null;
	}

	public static String doGet(String url) {
		String result = "";
		InputStream is = null;
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 访问https请求
			if (url.toLowerCase().startsWith("https")) {
				HttpsURLConnection httpsURLConnection = (HttpsURLConnection) conn;
				httpsURLConnection.setSSLSocketFactory(BZX509TrustManager.getSSFactory());
				httpsURLConnection.connect();
				is = httpsURLConnection.getInputStream();
			} else {
				conn.connect();
				is = conn.getInputStream();
			}
			if (is != null) {
				result = getHtmlBody(IOUtils.toString(is, getEncoding(realUrl)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	private static String getHtmlBody(String html){
		Document doc = Jsoup.parse(html);
		Elements es = doc.getElementsByTag("body");
		return es.iterator().next().html();
	}

	private static String getEncoding(URL url) {
		String defaltEncoding = "UTF-8";
		try {
			Document doc = Jsoup.parse(url, 100);
			Elements metas = doc.getElementsByTag("meta");
			Iterator<Element> eit = metas.iterator();
			while (eit.hasNext()) {
				String val = eit.next().attr("content");
				if (val != null && val.indexOf("text/html") > -1) {
					String[] s = val.split("=");
					if (s != null && s.length > 1) {
						defaltEncoding = s[1];
					}
					break;
				}
			}
		} catch (Exception e) {
		}
		return defaltEncoding;
	}

}
